package com.sunny.service.registry;

import com.sunny.service.ZKConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.util.StringUtils;

/**
 * @author Sunny
 * @date 2020/2/16
 */
@Slf4j
public class ZKRegistryService implements IRegistryService {

    private CuratorFramework curator;

    {
        curator = CuratorFrameworkFactory.builder()
                .connectString(ZKConfig.CONNECT_STRING)
                .namespace(ZKConfig.NAMESPACE)
                .sessionTimeoutMs(3000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        curator.start();
    }

    @Override
    public void registry(String serviceName, String address) {
        final String servicePath = "/" + serviceName;
        if (StringUtils.isEmpty(serviceName) || StringUtils.isEmpty(address)) {
            throw new RuntimeException("serviceName or address is empty!");
        }

        try {
            if (curator.checkExists().forPath(servicePath) == null) {
                curator.create().withMode(CreateMode.PERSISTENT).forPath(servicePath);
            }
            String addressPath = servicePath + "/" + address;
            curator.create().withMode(CreateMode.EPHEMERAL).forPath(addressPath, address.getBytes());
        } catch (Exception e) {
            log.error("create registry node exception!", e);
        }
        log.info("service: 【" + serviceName + "】register success!!");
    }
}
